import React, { useState, useEffect } from "react";
import {
  KeepAlive,
  AliveScope,
  useActivate,
  useUnactivate,
  useAliveController,
} from "react-activation";
import {
  Button,
  Tabs,
  Input,
  Card,
  Space,
  Typography,
  Alert,
  Divider,
  List,
  Tag,
  message,
} from "antd";
import "@/tailwind-variables.less";

const { Title, Text } = Typography;

// 计数器组件 - 演示状态保持
const Counter: React.FC<{ name: string }> = ({ name }) => {
  const [count, setCount] = useState(0);
  const [inputValue, setInputValue] = useState("");

  // 组件激活时的回调
  useActivate(() => {
    console.log(`${name} 组件被激活`);
  });

  // 组件失活时的回调
  useUnactivate(() => {
    console.log(`${name} 组件被失活`);
  });

  useEffect(() => {
    console.log(`${name} 组件挂载`);
    return () => {
      console.log(`${name} 组件卸载`);
    };
  }, [name]);

  return (
    <Card title={`${name} - 状态保持演示`} style={{ margin: "10px 0" }}>
      <Space direction="vertical" style={{ width: "100%" }}>
        <div>
          <Text strong>计数器: {count}</Text>
          <br />
          <Button
            type="primary"
            onClick={() => setCount(count + 1)}
            style={{ marginTop: 8 }}
          >
            增加计数
          </Button>
        </div>

        <div>
          <Text strong>输入框状态保持:</Text>
          <br />
          <Input
            placeholder="输入一些文字，切换标签页后再回来看看..."
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            style={{ marginTop: 8, width: 300 }}
          />
        </div>

        <div style={{ fontSize: 12, color: "#666", marginTop: 16 }}>
          <div>组件创建时间: {new Date().toLocaleTimeString()}</div>
          <div>当前输入内容: &quot;{inputValue}&quot;</div>
          <div>当前计数: {count}</div>
        </div>
      </Space>
    </Card>
  );
};

// 缓存控制器演示组件
const CacheController: React.FC = () => {
  const { drop, dropScope, refresh, clear, getCachingNodes } =
    useAliveController();
  const [cacheInfo, setCacheInfo] = useState<any[]>([]);

  // 获取缓存信息
  const updateCacheInfo = () => {
    try {
      const nodes = getCachingNodes();
      console.log("当前缓存节点数量:", nodes?.length || 0);
      setCacheInfo(nodes || []);
    } catch (error) {
      console.error("获取缓存信息失败:", error);
      setCacheInfo([]);
    }
  };

  useEffect(() => {
    updateCacheInfo();
    // 定期更新缓存信息
    const timer = setInterval(updateCacheInfo, 2000);
    return () => clearInterval(timer);
  }, [getCachingNodes]);

  // 清除特定缓存
  const handleDropCache = (name: string) => {
    try {
      console.log("尝试清除缓存:", name);
      drop(name);
      message.success(`已清除缓存: ${name}`);
      // 增加延迟，确保缓存清除完成
      setTimeout(updateCacheInfo, 500);
    } catch (error) {
      console.error("清除缓存失败:", error);
      message.error(`清除缓存失败: ${name}`);
    }
  };

  // 刷新特定缓存
  const handleRefreshCache = (name: string) => {
    try {
      console.log("尝试刷新缓存:", name);
      refresh(name);
      message.success(`已刷新缓存: ${name}`);
      setTimeout(updateCacheInfo, 300);
    } catch (error) {
      console.error("刷新缓存失败:", error);
      message.error(`刷新缓存失败: ${name}`);
    }
  };

  // 清除所有缓存
  const handleClearAll = () => {
    try {
      console.log("尝试清除所有缓存");
      clear();
      message.success("已清除所有缓存");
      setTimeout(updateCacheInfo, 300);
    } catch (error) {
      console.error("清除所有缓存失败:", error);
      message.error("清除所有缓存失败");
    }
  };

  // 清除作用域缓存
  const handleDropScope = () => {
    try {
      console.log("尝试清除作用域缓存");
      // dropScope 参数应该是 KeepAlive 的 name 属性值，可以用 String 或 RegExp 匹配
      // 这里使用正则表达式匹配所有以 "Counter" 开头的缓存（注意大小写）
      dropScope(/Counter.*/);
      message.success("已清除作用域缓存（匹配 Counter* 的组件）");
      setTimeout(updateCacheInfo, 300);
    } catch (error) {
      console.error("清除作用域缓存失败:", error);
      message.error("清除作用域缓存失败");
    }
  };

  return (
    <Card title="缓存控制器 - useAliveController" style={{ margin: "10px 0" }}>
      <Space direction="vertical" style={{ width: "100%" }}>
        <Alert
          message="缓存控制器功能"
          description={
            <div>
              <p>
                <strong>useAliveController</strong> 提供了手动控制缓存的能力：
              </p>
              <ul style={{ marginTop: 8, paddingLeft: 20 }}>
                <li>
                  <strong>drop(name)</strong>: 清除指定名称的缓存（参数为
                  KeepAlive 的 name 属性）
                </li>
                <li>
                  <strong>refresh(name)</strong>: 刷新指定名称的缓存
                </li>
                <li>
                  <strong>clear()</strong>: 清除所有缓存
                </li>
                <li>
                  <strong>dropScope(name)</strong>:
                  清除指定名称的缓存及其嵌套的所有缓存（参数为 KeepAlive 的 name
                  属性）
                </li>
                <li>
                  <strong>getCachingNodes()</strong>: 获取当前所有缓存节点信息
                </li>
              </ul>
            </div>
          }
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        <div>
          <Title level={5}>缓存控制操作</Title>
          <Space wrap>
            <Button type="primary" danger onClick={handleClearAll}>
              清除所有缓存
            </Button>
            <Button type="default" onClick={handleDropScope}>
              清除作用域缓存
            </Button>
            <Button type="default" onClick={updateCacheInfo}>
              刷新缓存信息
            </Button>
          </Space>
        </div>

        <div>
          <Title level={5}>当前缓存状态 ({cacheInfo.length} 个)</Title>
          {cacheInfo.length === 0 ? (
            <div>
              <Text type="secondary">暂无缓存组件</Text>
              <br />
              <Text type="secondary" style={{ fontSize: 12 }}>
                请先访问上面的标签页创建缓存，然后回到这里查看
              </Text>
            </div>
          ) : (
            <List
              size="small"
              bordered
              dataSource={cacheInfo}
              renderItem={(item: any, index: number) => {
                // 处理不同格式的缓存节点
                const cacheKey = item.cacheKey || item.key || `cache-${index}`;
                const name = item.name || item.displayName || cacheKey;

                return (
                  <List.Item
                    actions={[
                      <Button
                        key="refresh"
                        type="link"
                        size="small"
                        onClick={() => handleRefreshCache(name)}
                      >
                        刷新
                      </Button>,
                      <Button
                        key="drop"
                        type="link"
                        size="small"
                        danger
                        onClick={() => handleDropCache(name)}
                      >
                        清除
                      </Button>,
                    ]}
                  >
                    <List.Item.Meta
                      title={
                        <Space>
                          <Text strong>{name}</Text>
                          <Tag color="blue">{cacheKey}</Tag>
                        </Space>
                      }
                      description={
                        <div style={{ fontSize: 12 }}>
                          <div>
                            状态: <Tag color="green">已缓存</Tag>
                          </div>
                          <div>
                            节点类型:{" "}
                            {item.element?.type?.name ||
                              item.type?.name ||
                              "React组件"}
                          </div>
                          <div style={{ color: "#666", marginTop: 4 }}>
                            属性:{" "}
                            {Object.keys(item)
                              .filter((key) => !key.startsWith("_"))
                              .join(", ")}
                          </div>
                        </div>
                      }
                    />
                  </List.Item>
                );
              }}
            />
          )}
        </div>

        <div
          style={{ padding: 12, backgroundColor: "#f5f5f5", borderRadius: 4 }}
        >
          <Text strong>使用说明:</Text>
          <ol style={{ marginTop: 8, paddingLeft: 20, fontSize: 12 }}>
            <li>先在上面的标签页中操作，创建一些缓存的组件</li>
            <li>观察下方的缓存列表，查看当前有哪些组件被缓存</li>
            <li>点击&quot;刷新&quot;按钮重新渲染组件（状态会重置）</li>
            <li>点击&quot;清除&quot;按钮移除缓存（下次访问时会重新创建）</li>
            <li>使用&quot;清除所有缓存&quot;可以一次性清空所有缓存</li>
          </ol>

          <div
            style={{
              marginTop: 12,
              padding: 8,
              backgroundColor: "#e6f7ff",
              borderRadius: 4,
            }}
          >
            <Text strong style={{ color: "#1890ff" }}>
              关于 dropScope 参数：
            </Text>
            <ul style={{ marginTop: 4, paddingLeft: 16, fontSize: 11 }}>
              <li>
                <strong>drop(name)</strong>: 参数是 KeepAlive 的 name 属性值
              </li>
              <li>
                <strong>dropScope(name)</strong>: 同样是 KeepAlive 的 name
                属性值，但会清除嵌套的所有缓存
              </li>
              <li>
                参数支持 String 或 RegExp，例如：dropScope(/Counter.*/) 匹配所有
                Counter 开头的缓存
              </li>
              <li>
                <strong>AliveScope 组件本身不需要 name 属性</strong>
              </li>
            </ul>
          </div>
        </div>

        <div style={{ fontSize: 12, color: "#666", marginTop: 16 }}>
          <Text strong>实际应用场景:</Text>
          <ul style={{ marginTop: 4, paddingLeft: 16 }}>
            <li>用户登出时清除所有缓存</li>
            <li>数据更新后刷新特定页面缓存</li>
            <li>内存不足时主动清理缓存</li>
            <li>开发调试时检查缓存状态</li>
          </ul>
        </div>

        {cacheInfo.length > 0 && (
          <div
            style={{
              marginTop: 16,
              padding: 12,
              backgroundColor: "#f0f0f0",
              borderRadius: 4,
            }}
          >
            <Text strong>缓存节点概览:</Text>
            <div style={{ fontSize: 12, margin: "8px 0 0 0" }}>
              {cacheInfo.map((item, index) => (
                <div key={index} style={{ marginBottom: 4 }}>
                  <Tag color="blue">{item.cacheKey || `cache-${index}`}</Tag>
                  <span style={{ marginLeft: 8, color: "#666" }}>
                    {item.name || "未命名组件"}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
      </Space>
    </Card>
  );
};

// 原生React实现的伪"keep-alive"组件
const NativeCounter: React.FC<{
  name: string;
  isVisible: boolean;
  count: number;
  inputValue: string;
  onCountChange: (count: number) => void;
  onInputChange: (value: string) => void;
}> = ({ name, isVisible, count, inputValue, onCountChange, onInputChange }) => {
  useEffect(() => {
    console.log(`${name} (原生方式) 组件挂载`);
    return () => {
      console.log(`${name} (原生方式) 组件卸载`);
    };
  }, [name]);

  // 使用 display: none 隐藏而不是销毁组件
  return (
    <div style={{ display: isVisible ? "block" : "none" }}>
      <Card title={`${name} - 原生实现状态保持`} style={{ margin: "10px 0" }}>
        <Space direction="vertical" style={{ width: "100%" }}>
          <div>
            <Text strong>计数器: {count}</Text>
            <br />
            <Button
              type="primary"
              onClick={() => onCountChange(count + 1)}
              style={{ marginTop: 8 }}
            >
              增加计数
            </Button>
          </div>

          <div>
            <Text strong>输入框状态保持:</Text>
            <br />
            <Input
              placeholder="输入一些文字，切换标签页后再回来看看..."
              value={inputValue}
              onChange={(e) => onInputChange(e.target.value)}
              style={{ marginTop: 8, width: 300 }}
            />
          </div>

          <div style={{ fontSize: 12, color: "#666", marginTop: 16 }}>
            <div>组件创建时间: {new Date().toLocaleTimeString()}</div>
            <div>当前输入内容: &quot;{inputValue}&quot;</div>
            <div>当前计数: {count}</div>
            <div style={{ color: "#52c41a" }}>
              ✓ 使用原生React方法（状态提升 + 条件渲染）
            </div>
          </div>
        </Space>
      </Card>
    </div>
  );
};

// 列表组件 - 演示滚动位置保持
const ListComponent: React.FC = () => {
  const [items] = useState(() =>
    Array.from({ length: 50 }, (_, i) => `列表项 ${i + 1}`)
  );

  useActivate(() => {
    console.log("列表组件被激活");
  });

  useUnactivate(() => {
    console.log("列表组件被失活");
  });

  return (
    <Card title="列表组件 - 滚动位置保持" style={{ margin: "10px 0" }}>
      <div
        style={{
          height: 300,
          overflow: "auto",
          border: "1px solid #d9d9d9",
          padding: 16,
        }}
      >
        {items.map((item, index) => (
          <div
            key={index}
            style={{
              padding: 8,
              borderBottom: "1px solid #f0f0f0",
              backgroundColor: index % 2 === 0 ? "#fafafa" : "white",
            }}
          >
            {item} - 滚动测试项
          </div>
        ))}
      </div>
      <Text
        type="secondary"
        style={{ fontSize: 12, marginTop: 8, display: "block" }}
      >
        提示：滚动列表后切换到其他标签页，再回来时滚动位置会被保持
      </Text>
    </Card>
  );
};

// 表单组件 - 演示表单状态保持
const FormComponent: React.FC = () => {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    message: "",
  });

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  useActivate(() => {
    console.log("表单组件被激活");
  });

  useUnactivate(() => {
    console.log("表单组件被失活");
  });

  return (
    <Card title="表单组件 - 表单状态保持" style={{ margin: "10px 0" }}>
      <Space direction="vertical" style={{ width: "100%" }}>
        <div>
          <Text strong>姓名:</Text>
          <Input
            placeholder="请输入姓名"
            value={formData.name}
            onChange={(e) => handleChange("name", e.target.value)}
            style={{ marginTop: 4, width: 300 }}
          />
        </div>

        <div>
          <Text strong>邮箱:</Text>
          <Input
            placeholder="请输入邮箱"
            value={formData.email}
            onChange={(e) => handleChange("email", e.target.value)}
            style={{ marginTop: 4, width: 300 }}
          />
        </div>

        <div>
          <Text strong>留言:</Text>
          <Input.TextArea
            placeholder="请输入留言"
            value={formData.message}
            onChange={(e) => handleChange("message", e.target.value)}
            style={{ marginTop: 4, width: 300 }}
            rows={4}
          />
        </div>

        <div
          style={{
            marginTop: 16,
            padding: 12,
            backgroundColor: "#f5f5f5",
            borderRadius: 4,
          }}
        >
          <Text strong>当前表单数据:</Text>
          <pre style={{ fontSize: 12, margin: "8px 0 0 0" }}>
            {JSON.stringify(formData, null, 2)}
          </pre>
        </div>
      </Space>
    </Card>
  );
};

// 主组件
export const ReactActivation: React.FC = () => {
  const [activeKey, setActiveKey] = useState("counter1");

  // 原生方式的状态管理
  const [nativeActiveKey, setNativeActiveKey] = useState("native1");
  const [nativeStates, setNativeStates] = useState({
    native1: { count: 0, inputValue: "" },
    native2: { count: 0, inputValue: "" },
  });

  const updateNativeState = (
    key: "native1" | "native2",
    field: "count" | "inputValue",
    value: any
  ) => {
    setNativeStates((prev) => ({
      ...prev,
      [key]: {
        ...prev[key],
        [field]: value,
      },
    }));
  };

  return (
    <div style={{ padding: 20 }}>
      <Title level={2}>React 组件缓存方案对比</Title>

      <Alert
        message="React 组件缓存方案对比"
        description={
          <div>
            <p>
              <strong>React 本身没有原生的 keep-alive 功能</strong>
              ，以下是不同实现方案的对比：
            </p>
            <ul style={{ marginTop: 8 }}>
              <li>
                <strong>react-activation</strong>:
                第三方库，提供完整的组件缓存功能
              </li>
              <li>
                <strong>原生方案</strong>: 使用状态提升 + 条件渲染来模拟缓存效果
              </li>
              <li>
                <strong>Vue keep-alive</strong>: Vue 框架原生支持的组件缓存功能
              </li>
            </ul>
          </div>
        }
        type="info"
        showIcon
        style={{ marginBottom: 20 }}
      />

      {/* react-activation 示例 */}
      <Card
        title="方案一：使用 react-activation 库"
        style={{ marginBottom: 20 }}
      >
        <AliveScope>
          <Tabs
            activeKey={activeKey}
            onChange={setActiveKey}
            type="card"
            items={[
              {
                label: "计数器组件 A",
                key: "counter1",
                children: (
                  <KeepAlive cacheKey="counter-a" name="CounterA">
                    <Counter name="计数器 A (react-activation)" />
                  </KeepAlive>
                ),
              },
              {
                label: "计数器组件 B",
                key: "counter2",
                children: (
                  <KeepAlive cacheKey="counter-b" name="CounterB">
                    <Counter name="计数器 B (react-activation)" />
                  </KeepAlive>
                ),
              },
              {
                label: "列表组件",
                key: "list",
                children: (
                  <KeepAlive cacheKey="list-component" name="ListComponent">
                    <ListComponent />
                  </KeepAlive>
                ),
              },
              {
                label: "表单组件",
                key: "form",
                children: (
                  <KeepAlive cacheKey="form-component" name="FormComponent">
                    <FormComponent />
                  </KeepAlive>
                ),
              },
              {
                label: "缓存控制器",
                key: "controller",
                children: <CacheController />,
              },
            ]}
          />
        </AliveScope>
      </Card>

      <Divider />

      {/* 原生React实现 */}
      <Card
        title="方案二：使用原生 React 方法（状态提升 + 条件渲染）"
        style={{ marginBottom: 20 }}
      >
        <Tabs
          activeKey={nativeActiveKey}
          onChange={setNativeActiveKey}
          type="card"
          items={[
            {
              label: "计数器组件 A",
              key: "native1",
              children: (
                <NativeCounter
                  name="计数器 A"
                  isVisible={nativeActiveKey === "native1"}
                  count={nativeStates.native1.count}
                  inputValue={nativeStates.native1.inputValue}
                  onCountChange={(count) =>
                    updateNativeState("native1", "count", count)
                  }
                  onInputChange={(value) =>
                    updateNativeState("native1", "inputValue", value)
                  }
                />
              ),
            },
            {
              label: "计数器组件 B",
              key: "native2",
              children: (
                <NativeCounter
                  name="计数器 B"
                  isVisible={nativeActiveKey === "native2"}
                  count={nativeStates.native2.count}
                  inputValue={nativeStates.native2.inputValue}
                  onCountChange={(count) =>
                    updateNativeState("native2", "count", count)
                  }
                  onInputChange={(value) =>
                    updateNativeState("native2", "inputValue", value)
                  }
                />
              ),
            },
          ]}
        />
      </Card>

      {/* 对比说明 */}
      <Card title="方案对比分析">
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "1fr 1fr 1fr",
            gap: 16,
          }}
        >
          <Card
            size="small"
            title="react-activation"
            style={{ backgroundColor: "#f6ffed" }}
          >
            <div style={{ fontSize: 12 }}>
              <div style={{ color: "#52c41a", marginBottom: 8 }}>✅ 优点：</div>
              <ul style={{ paddingLeft: 16, margin: 0 }}>
                <li>使用简单，API 清晰</li>
                <li>自动处理组件生命周期</li>
                <li>支持滚动位置保持</li>
                <li>提供激活/失活钩子</li>
                <li>内存管理良好</li>
                <li>
                  <strong>支持手动缓存控制</strong>
                </li>
              </ul>
              <div style={{ color: "#ff4d4f", marginTop: 8, marginBottom: 8 }}>
                ❌ 缺点：
              </div>
              <ul style={{ paddingLeft: 16, margin: 0 }}>
                <li>需要额外依赖</li>
                <li>增加打包体积</li>
                <li>学习成本</li>
              </ul>
            </div>
          </Card>

          <Card
            size="small"
            title="原生 React 方案"
            style={{ backgroundColor: "#fff7e6" }}
          >
            <div style={{ fontSize: 12 }}>
              <div style={{ color: "#fa8c16", marginBottom: 8 }}>✅ 优点：</div>
              <ul style={{ paddingLeft: 16, margin: 0 }}>
                <li>无额外依赖</li>
                <li>完全可控</li>
                <li>性能可预测</li>
              </ul>
              <div style={{ color: "#ff4d4f", marginTop: 8, marginBottom: 8 }}>
                ❌ 缺点：
              </div>
              <ul style={{ paddingLeft: 16, margin: 0 }}>
                <li>代码复杂度高</li>
                <li>需要手动状态管理</li>
                <li>滚动位置难以保持</li>
                <li>容易出现内存泄漏</li>
                <li>组件仍然挂载在DOM中</li>
                <li>
                  <strong>缺少缓存控制能力</strong>
                </li>
              </ul>
            </div>
          </Card>

          <Card
            size="small"
            title="Vue keep-alive"
            style={{ backgroundColor: "#f0f5ff" }}
          >
            <div style={{ fontSize: 12 }}>
              <div style={{ color: "#1890ff", marginBottom: 8 }}>✅ 优点：</div>
              <ul style={{ paddingLeft: 16, margin: 0 }}>
                <li>框架原生支持</li>
                <li>使用简单</li>
                <li>性能优秀</li>
                <li>功能完整</li>
                <li>
                  <strong>支持include/exclude</strong>
                </li>
              </ul>
              <div style={{ color: "#ff4d4f", marginTop: 8, marginBottom: 8 }}>
                ❌ 限制：
              </div>
              <ul style={{ paddingLeft: 16, margin: 0 }}>
                <li>仅适用于 Vue</li>
                <li>React 无法使用</li>
              </ul>
            </div>
          </Card>
        </div>

        <div
          style={{
            marginTop: 16,
            padding: 12,
            backgroundColor: "#fafafa",
            borderRadius: 4,
          }}
        >
          <Title level={5}>总结建议：</Title>
          <ul style={{ paddingLeft: 20, margin: 0 }}>
            <li>
              如果项目对组件缓存有较高要求，推荐使用{" "}
              <strong>react-activation</strong>
            </li>
            <li>
              如果需要精确的缓存控制，<strong>useAliveController</strong>{" "}
              是最佳选择
            </li>
            <li>
              如果只是简单的状态保持，可以考虑<strong>原生方案</strong>
            </li>
            <li>
              如果使用 Vue 框架，直接使用 <strong>keep-alive</strong>
            </li>
          </ul>
        </div>
      </Card>

      <Card style={{ marginTop: 20 }}>
        <Title level={4}>测试步骤：</Title>
        <ol style={{ paddingLeft: 20 }}>
          <li>
            在&quot;计数器组件
            A&quot;中点击按钮增加计数，并在输入框中输入一些文字
          </li>
          <li>切换到&quot;计数器组件 B&quot;，进行类似操作</li>
          <li>在&quot;列表组件&quot;中滚动到中间位置</li>
          <li>在&quot;表单组件&quot;中填写一些表单数据</li>
          <li>
            <strong>在&quot;缓存控制器&quot;标签页中查看和管理缓存</strong>
          </li>
          <li>在不同标签页之间切换，观察状态是否被保持</li>
          <li>打开浏览器控制台查看生命周期钩子的执行情况</li>
          <li>对比两种方案的不同表现</li>
        </ol>
      </Card>
    </div>
  );
};
